package com.bestcem.xm.ticket.controller.convert;

import com.bestcem.xm.ticket.controller.vo.ticket.TicketInfoVO;
import com.bestcem.xm.ticket.controller.vo.ticket.TicketRecordVO;
import com.bestcem.xm.ticket.controller.vo.ticket.TicketTemplateVO;
import com.bestcem.xm.ticket.dao.dto.TicketInfo;
import com.bestcem.xm.ticket.entity.mongo.*;
import com.bestcem.xm.ticket.enums.FollowerFilterEnum;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.bestcem.xm.common.core.uitls.DateUtil.BEIJING_ZONE;
import static com.bestcem.xm.common.core.uitls.DateUtil.UTC_ZONE;

/**
 * entity/DTO => VO
 *
 * @author XiaoYunSong <ys.xiao@idiaoyan.com>
 * @version v1.0
 * @date 2021/9/9 22:28
 */
public class TicketInfoVOConvert {

    public static TicketInfoVO entityToTicketInfoVO(TicketInfo entity) {
        TicketInfoVO data = new TicketInfoVO();
        data.setName(entity.getName());
        data.setId(entity.getId());
        data.setOperationType(entity.getOperationType());
        data.setTicketNo(entity.getTicketNo());
        data.setRegionName(entity.getRegionName());
        data.setSurveyTitle(entity.getSurveyTitle());
        data.setStatus(entity.getStatus());
        data.setClosedDate(entity.getClosedDate());
        data.setHasFollowOverdue(entity.getHasFollowOverdue());
        if (Objects.nonNull(entity.getFollowDeadline())) {
            LocalDateTime localDateTime = LocalDateTime.ofInstant(entity.getFollowDeadline().toInstant(), UTC_ZONE);
            Date from = Date.from(localDateTime.toInstant(BEIJING_ZONE));
            data.setFollowDeadline(from);
        }
        if (Objects.nonNull(entity.getAuditDeadline())) {
            LocalDateTime localDateTime = LocalDateTime.ofInstant(entity.getAuditDeadline().toInstant(), UTC_ZONE);
            Date from = Date.from(localDateTime.toInstant(BEIJING_ZONE));
            data.setAuditDeadline(from);
        }

        data.setHasAuditOverdue(entity.getHasAuditOverdue());
        data.setAlertRecordId(entity.getAlertRecordId());
        data.setType(entity.getType());
        data.setNeedRecord(entity.getNeedRecord());
        data.setHasCommit(entity.getHasCommit());
        data.setRecordFlag(entity.getRecordFlag());
        data.setCreatedDate(entity.getCreatedDate());
        data.setCreatedId(entity.getCreatedId());
        data.setUpdatedDate(entity.getUpdatedDate());
        data.setUpdatedId(entity.getUpdatedId());
        data.setCreatedName(entity.getCreatedName());
        // 工单满足的触发条件的名称 2022-02-18 行动新增条件名称需求新增
        data.setTriggerNames(entity.getTriggerNames());
        if (CollectionUtils.isEmpty(data.getTriggerNames())) {
            data.setTriggerNames(new LinkedList<>());
        }

        data.setAlertRules(null);
        data.setLastAuditNode(false);
        data.setCurrentUsersIds(new ArrayList<>());
        data.setCurrentUsers(new ArrayList<>());
        data.setFollowerFilter(FollowerFilterEnum.REGION.getIndex());
        if (Objects.nonNull(entity.getTicketFlow()) && !CollectionUtils.isEmpty(entity.getTicketFlow().getFollowConfig())) {
            TicketFlow.FollowConfig followConfig = entity.getTicketFlow().getFollowConfig().get(0);
            if (Objects.nonNull(followConfig)) {
                data.setFollowerFilter(Optional.ofNullable(followConfig.getFollowerFilter()).orElse(FollowerFilterEnum.REGION.getIndex()));
            }
        }


        // 设置 工单详情模板
        data.setDetailTemplateId(entity.getDetailTemplateId());
        List<Ticket.TemplateDetailField> templateDetailFields = entity.getTemplateDetailFields();
        List<TicketInfoVO.TemplateDetailFieldVO> templateDetailFieldVOList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(templateDetailFields)) {
            for (Ticket.TemplateDetailField field : templateDetailFields) {
                TicketInfoVO.TemplateDetailFieldVO templateDetailFieldVO = new TicketInfoVO.TemplateDetailFieldVO();
                templateDetailFieldVO.setName(field.getContent());
                templateDetailFieldVO.setSourceId(field.getSourceId());
                templateDetailFieldVO.setOriginText(field.getOriginText());

                TicketInfoVO.TemplateDetailFieldVO.Value valueVO = new TicketInfoVO.TemplateDetailFieldVO.Value();
                Ticket.TemplateDetailField.SurveyAnswer value = field.getValue();
                if (Objects.nonNull(value)) {
                    valueVO.setAnswer(value.getAnswer());
                    valueVO.setCid(value.getCId());
                    valueVO.setCustomType(value.getCustomQType());
                    valueVO.setType(value.getQtype());
                }
                templateDetailFieldVO.setValue(valueVO);

                templateDetailFieldVOList.add(templateDetailFieldVO);
            }
        }
        data.setTemplateDetailFields(templateDetailFieldVOList);

        // 设置 工单处理模板
        TicketTemplateV2 ticketTemplateV2 = entity.getTicketTemplateV2();
        if (Objects.isNull(ticketTemplateV2)) {
            TicketTemplate ticketTemplate = entity.getTicketTemplate();
            if (Objects.nonNull(ticketTemplate)) {
                ticketTemplateV2 = TemplateConvert.convertOldTemplateToTemplateV2(ticketTemplate);
            }
        }
        data.setTicketTemplate(entityToTicketTemplateVO(ticketTemplateV2));

        // 设置 联系人信息
        Ticket.Contact contact = entity.getContact();
        if (Objects.nonNull(contact)) {
            TicketInfoVO.ContactVO contactVO = new TicketInfoVO.ContactVO();
            contactVO.setPhone(contact.getPhone());
            contactVO.setEmail(contact.getEmail());
            data.setContact(contactVO);
        }

        // 设置 工单记录
        List<TicketRecord> ticketRecords = entity.getTicketRecords();
        List<TicketRecordVO> ticketRecordVOS = new ArrayList<>();
        if (!CollectionUtils.isEmpty(ticketRecords)) {
            for (TicketRecord ticketRecord : ticketRecords) {
                ticketRecordVOS.add(entityToTicketRecordVO(ticketRecord));
            }
        }
        data.setTicketRecords(ticketRecordVOS);

        return data;
    }


    private static List<TicketTemplateVO.CascadeVO.OptionVO> optionToVoList(List<TicketTemplateV2.Option> options) {
        if (options == null) {
            return null;
        }
        List<TicketTemplateVO.CascadeVO.OptionVO> list = new ArrayList<>(options.size());
        for (TicketTemplateV2.Option option : options) {
            list.add(optionToVo(option));
        }

        return list;
    }

    private static TicketTemplateVO.CascadeVO.OptionVO optionToVo(TicketTemplateV2.Option option) {
        if (option == null) {
            return null;
        }
        TicketTemplateVO.CascadeVO.OptionVO optionVO = new TicketTemplateVO.CascadeVO.OptionVO();
        optionVO.setId(option.getId());
        optionVO.setPid(option.getPid());
        optionVO.setValue(option.getValue());
        return optionVO;
    }

    private static List<TicketTemplateVO.CascadeVO> cascadeToVos(List<TicketTemplateV2.Cascade> cascades) {
        if (cascades == null) {
            return null;
        }
        List<TicketTemplateVO.CascadeVO> list = new ArrayList<>(cascades.size());
        for (TicketTemplateV2.Cascade cascade : cascades) {
            list.add(cascadeToVo(cascade));
        }

        return list;
    }

    private static TicketTemplateVO.CascadeVO cascadeToVo(TicketTemplateV2.Cascade cascades) {
        if (cascades == null) {
            return null;
        }

        TicketTemplateVO.CascadeVO cascadeVO = new TicketTemplateVO.CascadeVO();

        cascadeVO.setLevel(cascades.getLevel());
        cascadeVO.setOptions(optionToVoList(cascades.getOptionList()));
        return cascadeVO;
    }


    private static TicketTemplateVO entityToTicketTemplateVO(TicketTemplateV2 entity) {
        if (Objects.isNull(entity)) {
            return null;
        }
        TicketTemplateVO data = new TicketTemplateVO();
        data.setId(entity.getId());
        data.setOrgId(entity.getOrgId());
        data.setTicketConfigId(entity.getTicketConfigId());
        data.setRecordFlag(entity.getRecordFlag());
        data.setCreatedDate(entity.getCreatedDate());
        data.setCreatedId(entity.getCreatedId());
        data.setUpdatedDate(entity.getUpdatedDate());
        data.setUpdatedId(entity.getUpdatedId());
        // 历史字段, 附默认值
        data.setCategory(0);
        data.setCustomFieldLimit(0);
        data.setDefaultFields(new ArrayList<>());

        List<TicketTemplateVO.FieldInfoVO> customFields = new ArrayList<>();
        if (!CollectionUtils.isEmpty(entity.getFieldList())) {
            // 历史数据先排序后进行赋值
            List<TicketTemplateV2.FieldInfo> fieldInfos = entity.getFieldList().stream()
                    .sorted(Comparator.comparingInt(TicketTemplateV2.FieldInfo::getIsUpdate))
                    .collect(Collectors.toList());
            boolean hasDefault = false;
            for (TicketTemplateV2.FieldInfo fieldInfo : fieldInfos) {
                // 兼容线上错误工单数据
                if ("处理记录".equals(fieldInfo.getName()) && Integer.valueOf(2).equals(fieldInfo.getType())
                        && fieldInfo.getRequired() && "field0".equals(fieldInfo.getField())) {
                    hasDefault = true;
                }
                TicketTemplateVO.FieldInfoVO fieldInfoVO = new TicketTemplateVO.FieldInfoVO();
                fieldInfoVO.setName(fieldInfo.getName());
                fieldInfoVO.setType(fieldInfo.getType());
                fieldInfoVO.setRequired(fieldInfo.getRequired());
                fieldInfoVO.setField(fieldInfo.getField());

                // 设置 单选数据选项
                TicketTemplateV2.SingleSelect singleSelect = fieldInfo.getSingleSelect();
                fieldInfoVO.setSingleSelect(singleSelect);

                // 级联数据数组
                List<TicketTemplateV2.Cascade> cascadeList = fieldInfo.getCascadeList();
                List<TicketTemplateVO.CascadeVO> cascadeVOS = TicketInfoVOConvert.cascadeToVos(cascadeList);
                fieldInfoVO.setCascades(cascadeVOS);
                customFields.add(fieldInfoVO);
            }
            if (!hasDefault) {
                TicketTemplateVO.FieldInfoVO fieldInfoVO = new TicketTemplateVO.FieldInfoVO();
                fieldInfoVO.setName("处理记录");
                fieldInfoVO.setType(2);
                fieldInfoVO.setRequired(true);
                fieldInfoVO.setField("field0");
                customFields.add(0, fieldInfoVO);
            }
        }
        data.setCustomFields(customFields);
        return data;
    }

    private static TicketRecordVO entityToTicketRecordVO(TicketRecord entity) {
        if (Objects.isNull(entity)) {
            return null;
        }

        TicketRecordVO data = new TicketRecordVO();
        data.setId(entity.getId());
        data.setRecordFlag(entity.getRecordFlag());
        data.setCreatedDate(entity.getCreatedDate());
        data.setCreatedId(entity.getCreatedId());
        data.setUpdatedDate(entity.getUpdatedDate());
        data.setUpdatedId(entity.getUpdatedId());
        data.setOrgId(entity.getOrgId());
        data.setUserId(entity.getUserId());
        data.setTitle(entity.getTitle());
        data.setTicketId(entity.getTicketId());
        data.setRoleId(entity.getRoleId());
        data.setRegion(entity.getRegion());
        data.setRegionName(entity.getRegionName());
        data.setUserName(entity.getUserName());
        data.setSource(entity.getSource());
        Integer event = entity.getEvent();
        data.setEvent(event);
        data.setSurveyId(entity.getSurveyId());
        data.setTicketStatus(entity.getTicketStatus());
        data.setCustomAttr(TicketRecordVO.CustomAttrVO.getInstance(entity.getCustomAttr()));

        //  2.3 新增字段接受转派的用户
        data.setTransferUsername(entity.getReceiveUserName());

        // 2.3 新增字段，工单原因
        data.setReason(entity.getReason());

        return data;
    }
}
